﻿using System;
using System.Collections.Generic;
using AxeSoftware.Quest;

namespace QuestConsole
{
    public class Runner
    {
        private readonly string _mFilename;
        private ConsolePlayer _mPlayer;
        private PlayerHelper _mHelper;
        private bool _mRunning = true;

        public Runner(string filename)
        {
            _mFilename = filename;
        }

        public void Start()
        {
            IASL game = GameLauncher.GetGame(_mFilename, null);

            _mPlayer = new ConsolePlayer(game);
            _mPlayer.ClearBuffer += ClearBuffer;
            _mPlayer.Finish += Finish;
            _mHelper = new PlayerHelper(game, _mPlayer);

            List<string> errors;
            if (!_mHelper.Initialise(_mPlayer, out errors))
            {
                Console.WriteLine(@"Failed to load game");
                foreach (var error in errors)
                {
                    Console.WriteLine(error);
                }
                Console.ReadKey();
            }
            else
            {
                game.Begin();
                PlayGame();
            }
        }

        private void Finish()
        {
            _mRunning = false;
            ClearBuffer();
        }

        private void ClearBuffer()
        {
            _mPlayer.OutputText(_mHelper.ClearBuffer());
        }

        private void PlayGame()
        {
            do
            {
                ClearBuffer();
                string input = Console.ReadLine();

                _mHelper.SendCommand(input, _mPlayer.GetTickCountAndStopTimer());
            } while (_mRunning);
        }
    }
}
